﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PhotoList.Web.User
{
    public partial class ucList : System.Web.UI.UserControl
    {       

        #region Attributes

        protected string PictureDirectory = ConfigurationManager.AppSettings["HomeDirectory"];
        protected string ThumbnailPath = ConfigurationManager.AppSettings["ThumbnailPath"];
        protected string ThumbnailWidth=ConfigurationManager.AppSettings["ThumbnailWidth"];
        protected string ThumbnailHeight = ConfigurationManager.AppSettings["ThumbnailHeight"];            
        protected string userHome = ""; //用户主目录
        protected string pathDir = "";  //当前图片目录
        protected string pathURL = "";

        protected string PicList = "";
        protected string Pageing = "";

        //分页
        protected int pageno = 1;
        protected int totalcount = 1;
        protected int pagecount = 1;
        protected int pagesize = Convert.ToInt16(ConfigurationManager.AppSettings["PageSize"]);

        #endregion

        #region Transfer Attributes

        public string Path ="/";
        public string Keywords = "";
        public string IsFull = "0";
        public string IsCase = "0";
        public string IsRegular = "0";

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(Request.QueryString["page"]))
            {
                pageno = 1;
            }
            else
            {
                if(!int.TryParse(Request.QueryString["page"],out pageno))
                {
                    pageno = 1;
                }
            }

            if (PictureDirectory.EndsWith("/") || PictureDirectory.EndsWith(@"\"))
            {
                PictureDirectory = PictureDirectory.Remove(PictureDirectory.Length - 1);
            }

            if (!GetHome()) return;

            if (!GetDirectory()) return;

            DirectoriesList();

            InitPageing();
        }

        private bool GetHome()
        {
            PhotoList.Dal.User uUser = new PhotoList.Dal.User(Session["QT_UID"].ToString());

            if (uUser.Home == "")
            {
                new QT.Basic.Tools().Alert("未设置用户主目录");
                return false;
            }

            userHome = uUser.Home;

            if (!userHome.StartsWith("/") && !userHome.StartsWith(@"\"))
            {
                userHome = "/" + uUser.Home;
            }

            if (userHome.EndsWith("/") || userHome.EndsWith(@"\"))
            {
                userHome = userHome.Remove(userHome.Length - 1);
            }

            if (!Directory.Exists(Server.MapPath(PictureDirectory + userHome)))
            {
                new QT.Basic.Tools().Alert("用户主目录不存在");
                return false;
            }

            return true;
        }

        private bool GetDirectory()
        {
            if (string.IsNullOrEmpty(Request.QueryString["dir"])) pathDir = "";
            else pathDir = Request.QueryString["dir"];

            if (!pathDir.StartsWith("/") && pathDir != "") pathDir = "/" + pathDir;

            string[] dirs = pathDir.Split('/');
            for (int i = 0; i < dirs.Length; i++)
            {
                if (i + 1 == dirs.Length)
                {
                    this.lblDirectory.Text += dirs[i] == "" ? "" : " / " + dirs[i];
                }
                else
                {
                    pathURL += i == 0 ? "" : "/" + dirs[i];
                    this.lblDirectory.Text += dirs[i] == "" ? "" : " / <a href=\"Main.aspx?target=User/ucList&dir=" + pathURL + "\" target=\"_self\">" + dirs[i] + "</a>";
                }
            }

            if (!Directory.Exists(Server.MapPath(PictureDirectory)))
            {
                new QT.Basic.Tools().Alert("目录不存在");
                return false;
            }            

            return true;
        }

        private void DirectoriesList()
        {
            DataTable dt = PhotoList.Dal.IO.GetAll(PictureDirectory + userHome + pathDir);

            totalcount = dt.Rows.Count;
            pagecount = (totalcount % pagesize == 0) ? (totalcount / pagesize) : (totalcount / pagesize + 1);

            for (int i = pagesize * (pageno - 1); i < pagesize * pageno; i++)
            {
                if (i >= totalcount) break;
                switch (dt.Rows[i]["type"].ToString())
                {
                    case "-1":
                        PicList += "<div class=\"div\" style=\"text-align:center; \"><a href=\"" + Request.Url.AbsolutePath + "?target=User/ucList&dir=" + pathDir + "/" + dt.Rows[i]["name"].ToString() + "\" title=" + dt.Rows[i]["name"].ToString() + "\" target=\"_self\"><div class=\"divimg\" title=\"" + dt.Rows[i]["name"].ToString() + "\"><img src=\"/img/filetype/Directory.png\" alt=\"" + dt.Rows[i]["name"].ToString() + "\" title=\"" + dt.Rows[i]["name"].ToString() + "\" onload=\"changeImg(this," + ThumbnailWidth + "," + ThumbnailHeight + ")\" /></div><div class=\"divlink\">" + dt.Rows[i]["shortname"].ToString() + "</div></a></div>\n\t";
                        break;
                    case "0":
                        PicList += "<div class=\"div\" style=\"text-align:center; \"><a href=\"" + PictureDirectory + userHome + pathDir + "/" + dt.Rows[i]["name"].ToString() + "\" title=" + dt.Rows[i]["name"].ToString() + "\" target=\"_blank\"><div class=\"divimg\" title=\"" + dt.Rows[i]["name"].ToString() + "\"><img  alt=\"" + dt.Rows[i]["name"].ToString() + "\" title=\"" + dt.Rows[i]["name"].ToString() + "\" onload=\"changeImg(this," + ThumbnailWidth + "," + ThumbnailHeight + ")\" /></div><div class=\"divlink\">" + dt.Rows[i]["shortname"].ToString() + "</div></a></div>\n\t";
                        break;
                    case "1":
                        PicList += "<div class=\"div\" style=\"text-align:center; \"><a href=\"" + PictureDirectory + userHome + pathDir + "/" + dt.Rows[i]["name"].ToString() + "\" title=\"" + dt.Rows[i]["name"].ToString() + "\" target=\"_blank\"><div class=\"divimg\" title=\"" + dt.Rows[i]["name"].ToString() + "\"><object><param name=\"movie\" value=\"" + PictureDirectory + userHome + pathDir + "/" + dt.Rows[i]["name"].ToString() + "\" /><param name=\"quality\" value=\"high\" /><param name=\"wmode\" value=\"transparent\" /><embed src=\"" + PictureDirectory + userHome + pathDir + "/" + dt.Rows[i]["name"].ToString() + "\" quality=\"high\" wmode=\"transparent\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" width=\"" + ThumbnailWidth + "\" height=\"" + ThumbnailHeight + "\"></embed></object></div><div class=\"divlink\">" + dt.Rows[i]["shortname"].ToString() + "</div></a></div>\n\t";
                        break;
                    default:
                        string icoFile = "/img/filetype/" + dt.Rows[i]["ext"].ToString() + ".png";
                        if (!File.Exists(Server.MapPath(icoFile))) icoFile = "/img/filetype/UnKnown.png";
                        PicList += "<div class=\"div\" style=\"text-align:center; \"><a href=\"" + PictureDirectory + userHome + pathDir + "/" + dt.Rows[i]["name"].ToString() + "\" title=\"" + dt.Rows[i]["name"].ToString() + "\" target=\"_blank\"><div class=\"divimg\" title=\"" + dt.Rows[i]["name"].ToString() + "\"><img src=\"" + icoFile + "\" class=\"img\" title=\"" + dt.Rows[i]["name"].ToString() + "\" onload=\"changeImg(this," + ThumbnailWidth + "," + ThumbnailHeight + ")\" /></div><div class=\"divlink\">" + dt.Rows[i]["shortname"].ToString() + "</div></a></div>\n\t";
                        break;
                }
            }
        }

        private void InitPageing()
        {
            Pageing += "<div class=\"Pageing\">";
            Pageing += "<div style=\"float:left\">";
            Pageing += "共" + pagecount + "页" + totalcount + "个文件(夹)，当前第" + pageno + "页" + ((pageno - 1) * pagesize + 1) + "-" + ((pageno * pagesize) > totalcount ? totalcount : (pageno * pagesize)) + "个文件(夹)";
            Pageing += "</div>";

            Pageing += "<div style=\"float:right\">";
            if (pagecount > 1)
            {
                if (pageno > 1)
                {
                    Pageing += "<a href=\"" + Request.Url.AbsolutePath + "?target=User/ucList&dir=" + pathDir+"\" target=\"_self\">第一页</a>&nbsp;<a href=\"" + Request.Url.AbsolutePath + "?target=User/ucList&dir=" + pathDir + "&page=" + (pageno - 1) + "\" target=\"_self\">上一页</a>&nbsp;";
                }
                for (int i = 1; i <= pagecount; i++)
                {
                    if (i == pageno)
                    {
                        Pageing += i + "&nbsp;";
                    }
                    else
                    {
                        Pageing += "<a href=\"" + Request.Url.AbsolutePath + "?target=User/ucList&dir=" + pathDir + "&page=" + i + "\" target=\"_self\">" + i + "</a>&nbsp;";
                    }
                }
                if (pageno < pagecount)
                {
                    Pageing += "<a href=\"" + Request.Url.AbsolutePath + "?target=User/ucList&dir=" + pathDir + "&page=" + (pageno + 1) + "\" target=\"_self\">下一页</a>&nbsp;<a href=\"" + Request.Url.AbsolutePath + "?target=User/ucList&dir=" + pathDir + "&page=" + pagecount + "\" target=\"_self\">最后页</a>";
                }
            }

            Pageing += "</div>";
            Pageing += "</div>";
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.tbKeywords.Text))
            {
                new QT.Basic.Tools().Alert("请输入搜索关键字");
                return;
            }
            if (!this.rbtCurrentDir.Checked && !this.rbtAllSite.Checked)
            {
                new QT.Basic.Tools().Alert("请选择搜索范围");
                return;
            }

            Keywords = this.tbKeywords.Text;
            if (this.rbtCurrentDir.Checked) Path = pathDir;
            if (this.cbFullKeywords.Checked) IsFull = "1";
            if (this.cbCase.Checked) IsCase = "1";
            if (this.cbRegular.Checked) IsRegular = "1";

            Response.Redirect("main.aspx?target=User/ucSearch&path=" + Path + "&keywords=" + Keywords + "&isfull=" + IsFull + "&iscase=" + IsCase + "&isregular=" + IsRegular);
        }
    }
}